import { defineComponent, watch, ref,onUnmounted, onMounted,} from 'vue';
import * as echarts from 'echarts';
// 定义 props 类型
interface Props {
  cdata: {
    category: string[];
    rateData: number[];
    barData: number[];
    lineData: number[];
  };
}

// 定义子组件
const Draw = defineComponent({
  props: {
    cdata: {
      type: Object as () => Props['cdata'],
      required: true
    }
  },
  setup(props: Props) {
    // 定义 ref 用于获取图表的 DOM 元素
    const chartRef = ref<HTMLDivElement | null>(null);
    // 定义 ECharts 实例
    let myChart: echarts.ECharts | null = null;

    // 计算 y 轴最大和最小值
    const calculateYAxisRange = (data: number[]) => {
      const max = Math.max(...data);
      const min = Math.min(...data);
      const range = max - min;
      const center = (max + min) / 2;
      const halfRange = range / 2;
      return {
        min: center - halfRange,
        max: center + halfRange
      };
    };

    // 生成 ECharts 图表配置项的函数
    const generateOptions = (val: Props['cdata']) => {
      const barLineData = [...val.barData, ...val.lineData];
      const barLineYAxisRange = calculateYAxisRange(barLineData);

      // 计算每条柱状图数据的一半作为折线数据
      const newRateData = val.barData.map((barValue, index) => {
        const lineValue = val.lineData[index];
        return Math.max(barValue, lineValue) / 2;
      });

      return {
        tooltip: {
          show: true,
          trigger: 'item',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: 'red'
            }
          }
        },
        legend: {
          show: true
        },
        grid: {
          x: '8%',
          width: '88%',
          top: '5%',
          bottom: '7%'
        },
        xAxis: {
          data: val.category,
          axisLine: {
            lineStyle: {
              color: '#B4B4B4'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: [
          {
            splitLine: { 
              show: false // 移除 y 轴分割线
            },
            axisLine: {
              lineStyle: {
                color: '#B4B4B4'
              }
            },
            axisLabel: {
              formatter: '{value} '
            },
            min: barLineYAxisRange.min,
            max: barLineYAxisRange.max,
            markLine: {
              data: [
                {
                  yAxis: (barLineYAxisRange.max + barLineYAxisRange.min) / 2,
                  lineStyle: {
                    color: 'red',
                    type: 'solid'
                  }
                }
              ]
            }
          }
        ],
        series: [
          {
            name: '贯通率',
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#38cdb9'
              }
            },
            data: newRateData
          },
          {
            name: '已贯通',
            type: 'bar',
            barWidth: 10,
            itemStyle: {
              normal: {
                barBorderRadius: 5,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#38cdb9' },
                  { offset: 1, color: '#176172' }
                ])
              }
            },
            data: val.barData
          },
          {
            name: '计划贯通',
            type: 'bar',
            barGap: '-100%',
            barWidth: 10,
            itemStyle: {
              normal: {
                barBorderRadius: 5,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#005361' },
                  { offset: 0.2, color: '#176172' },
                  { offset: 1, color: '#38cdb9' }
                ])
              }
            },
            z: -12,
            data: val.lineData
          }
        ]
      };
    };

    // 初始化 ECharts 图表的函数
    const initChart = () => {
      if (chartRef.value) {
        myChart = echarts.init(chartRef.value);
        const options = generateOptions(props.cdata);
        // 第二个参数设置为 true 开启动画
        myChart.setOption(options, true);
      }
    };

    // 更新图表数据的函数
    const updateChartData = (val: Props['cdata']) => {
      if (myChart) {
        const newOptions = generateOptions(val);
        // 第二个参数设置为 true 开启动画
        myChart.setOption(newOptions, true);
      }
    };

    // 监听 props.cdata 的变化，数据变化时调用 updateChartData 函数更新图表
    watch(
      () => props.cdata,
      (val) => {
        updateChartData(val);
      },
      {
        immediate: true,
        deep: true
      }
    );

    // 组件挂载时调用 initChart 函数初始化图表
    onMounted(() => {
      initChart();
    })

    // 组件卸载时销毁 ECharts 实例，避免内存泄漏
     onUnmounted(() => {
      if (myChart) {
        myChart.dispose();
      }
    })

    // 返回 JSX 元素，设置图表容器的样式
    return () => (
      <div ref={chartRef} style={{ width: '100%', height: '450px' }}></div>
    );
  }
});

export default Draw;